package com.polaris.live.push

import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.manager.withRetryNow
import com.polaris.live.common.util.LogExt
import com.polaris.live.manager.GooglePushManager
import com.polaris.live.manager.PromptNoticeManager
import com.polaris.live.net.userService
import com.polaris.live.resp.go_resp.FcmNoticeTokenBean
import kotlinx.coroutines.launch

/**
 * PushFirebaseMessagingService
 *
 * @author Created by lucas on 2023/12/11 08:04
 */
class PushFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(message: RemoteMessage) {
        PromptNoticeManager.showNotice(message)

        LogExt.logI("--firebase", message.toString())
    }

    override fun onDeletedMessages() {
        super.onDeletedMessages()

        LogExt.logI("--firebase", "onDeletedMessages")
    }

    override fun onNewToken(token: String) {
        if (!AppModule.checkGoogleServices()) return

        GooglePushManager.setFcmToken(token)

        if (UserManager.isLogin()) {
            CoroutineScopeManager.ioScope.launch {
                withRetryNow {
                    userService.fcmNoticeToken(FcmNoticeTokenBean(token))
                }
            }
        }

        LogExt.logI("--firebase", "token = $token")
    }
}